package com.ig.amazon.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.a2s.model.Item;
import com.amazonaws.a2s.model.ItemLookupResponse;
import com.amazonaws.a2s.model.ItemSearchResponse;
import com.amazonaws.a2s.model.Items;
import com.ig.model.Search;

/**
 * AmazonServiceImpl is the implementation class for Amazon services
 * 
 * @author skodali
 * 
 */
public class AmazonServiceImpl implements AmazonService {

	protected AmazonServiceImpl() {

	}

	/** Tries to retrieve product info from Amazon ECS. */
	public Item retrieveProductFromAmazonECS(String productType, String ean)
			throws Exception {
		Item item = null;
		try {
			String searchIndex = productType;
			List<String> responseGroups = new ArrayList<String>();
			addResponseGroups(responseGroups);
			ItemLookupResponse response = AmazonServiceUtil.retrieveItemsInfo(
					getBookNumberType(ean), ean, searchIndex, responseGroups);
			item = AmazonServiceUtil.getItemByProductCode(response, true, ean);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return item;
	}

	/** Tries to retrieve products info from Amazon ECS. */
	public List<Items> retrieveProductsFromAmazon(Search searchCriteria)
			throws Exception {
		List<Items> items = null;
		try {
			searchCriteria
					.setResponseGroups(addResponseGroupsForDetailedSearch());
			ItemSearchResponse response = AmazonServiceUtil
					.retrieveAmazonsResponse(searchCriteria);
			items = AmazonServiceUtil.getItems(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return items;
	}

	/** add the response groups */
	private static void addResponseGroups(List<String> responseGroups) {
		responseGroups.add(AmazonServiceConstants.ItemAttributes);
	}

	/** add the response groups */
	private static List<String> addResponseGroupsForDetailedSearch() {
		List<String> responseGroups = new ArrayList<String>();
		responseGroups.add(AmazonServiceConstants.ItemAttributes);
		responseGroups.add(AmazonServiceConstants.OfferSummary);
		return responseGroups;
	}

	/** return the book Identification number type */
	private static String getBookNumberType(String ean) {
		if (ean.length() >= 13)
			return AmazonServiceConstants.EAN;
		else
			return AmazonServiceConstants.ISBN;
	}

}
